/**  
 * @Title: SmsServiceImpl.java
 * @Package org.wk.common.service
 * @Description: TODO【】
 * @author df.w 
 * @date 2018年5月3日 下午5:01:58
 * @version V1.0  
 */ 

package org.wk.common.service;

import java.util.Date;

import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.wk.common.dao.SmsDao;
import org.wk.common.domain.Sms;
import org.wk.common.enums.ResponseCode;
import org.wk.common.enums.SmsCodeType;
import org.wk.common.enums.SmsSendStatus;
import org.wk.common.sms.SendMsg_webchinese;
import org.wk.common.sms.TelMsgUtil;
import org.wk.core.common.tool.GeneratorStringUtils;
import org.wk.core.common.tool.RegexUtils;
import org.wk.core.common.view.ResponseVo;
import org.wk.user.dao.UserDao;
import org.wk.user.domain.User;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;

/**
 * @ClassName	: SmsServiceImpl
 * @Package		：org.wk.common.service
 * @Author df.w 
 * @Create Time	：2018年5月3日 下午5:01:58
 * @Description	: 
 */
@Service
public class SmsServiceImpl implements SmsService {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private SmsDao smsDao;
	
	@Autowired
	private UserDao userDao;
	
	
	
	/* (非 Javadoc)
	 * <p>Title: sendSms</p>
	 * <p>Description: </p>
	 * @param mobileNumber
	 * @param smsCode
	 * @param smsCodeType
	 * @param expireTime
	 * @return
	 * @see org.wk.common.service.SmsService#sendSms(java.lang.String, java.lang.String, java.lang.String, int)
	 */
	private ResponseVo send(String mobileNumber, String smsCode, String smsCodeType, int expireTime) {

		Sms sms = new Sms();
		sms.setMobileNumber(mobileNumber);
		sms.setSmsCode(smsCode);
		sms.setSmsCodeType(smsCodeType);
		sms.setStatus(SmsSendStatus.UNSENT.getCode());
		sms = smsDao.save(sms);

		String code = SendMsg_webchinese.sendSms(mobileNumber,smsCode);
		logger.info(code);
		if ("OK".equals(code)) {
			sms.setSendTime(new Date());
			sms.setStatus(SmsSendStatus.SENT_SUCCESS.getCode());
			sms.setExpireTime(new DateTime(sms.getSendTime()).plusMinutes(expireTime).toDate());
			smsDao.update(sms);
			return new ResponseVo().success();
		} 
		//如果触发分钟控制流，则返回成功
		if ("isv.BUSINESS_LIMIT_CONTROL".equals(code)) {
			smsDao.delete(sms);
			return new ResponseVo().success();
		}
		
		sms.setSendTime(new Date());
		sms.setStatus(SmsSendStatus.SENT_FAIL.getCode());
		smsDao.update(sms);
		return new ResponseVo().error();
	}




	
	/* (非 Javadoc)
	 * <p>Title: sendSms</p>
	 * <p>Description: </p>
	 * @param jsonObject
	 * @return
	 * @see org.wk.common.service.SmsService#sendSms(com.alibaba.fastjson.JSONObject)
	 */ 
	
	@Override
	public ResponseVo sendSms(JSONObject jsonObject) {
		// TODO Auto-generated method stub
		//验证手机号码
		String mobileNumber = jsonObject.getString("mobile_number");
		if (!RegexUtils.checkMobileNum(mobileNumber)) {
			return new ResponseVo(ResponseCode.MOBILE_NUMBER_ERROR);
		}
		
		//验证短信验证码类型
		String codeType = jsonObject.getString("code_type");
		if (null == SmsCodeType.containsCode(codeType)) {
			return new ResponseVo(ResponseCode.SMS_CODE_TYPE_ERROR); 
		}
		//如果是注册的时候需要判断该用户是否已经存在，如果存在则不发送验证码
		if (SmsCodeType.REGISTER.getCode().equals(codeType)) {
			boolean forceUserNonexise = jsonObject.getBooleanValue("force_user_nonexist"); 
			//如果需要验证手机号码是否已存在
			if (forceUserNonexise) {
				User user = userDao.findByMobileNumber(mobileNumber);
				if (user!=null) {
					return new ResponseVo(ResponseCode.MOBILE_NUMBER_EXIST);
				}
				
			}
		}
		//如果是重置密码，则改手机号必须已经注册过
		if (SmsCodeType.RESET_PASSWORD.getCode().equals(codeType)) {
			User user = userDao.findByMobileNumber(mobileNumber);
			if (user==null) {
				return new ResponseVo(ResponseCode.MOBILE_NUMBER_UNREGISTERED);
			}
		}
		
		//生成验证码
		String smsCode = GeneratorStringUtils.createRandomNumString(6);
		//发送验证码
		return send(mobileNumber, smsCode, codeType, 2);
		
	}

	/* (非 Javadoc)
	 * <p>Title: checkSmsCode</p>
	 * <p>Description: </p>
	 * @param mobileNum
	 * @param smsCode
	 * @param smsCodeType
	 * @return
	 * @see org.wk.common.service.SmsService#checkSmsCode(java.lang.String, java.lang.String, java.lang.String)
	 */ 
	
	@Override
	public boolean checkSmsCode(String mobileNum, String smsCode, String smsCodeType) {
		// TODO Auto-generated method stub
		Date now = new Date();		
		Sms sms = smsDao.findByMobileNumberAndSmsCodeTypeGreaterThanExpireTimeLimit1(mobileNum,smsCodeType,now);		
		if (sms!=null && smsCode.equals(sms.getSmsCode())) {	
			return true;
		}      
        return false;
	}

}
